<!-- 首页页面 -->
<template>
  <div class="page-container">
    <div class="page-bg">
      <image
        class="page-bg__img"
        src="https://ustatic.hudongmiao.com/miao/web/top-fw.png"
        mode="widthFix"
      />
    </div>
    <!-- 活动规则按钮 -->
    <div class="activity-rule-btn" @click="rulesPopup?.open">规则</div>
    <!-- 分享好友按钮 -->
    <div class="share-friend-btn">
      分享
      <button class="hidden-btn" open-type="share" />
    </div>
    <!-- 「立即组团」面板 -->
    <div class="join-panel">
      <!-- 没有团队的情况 -->
      <div class="join-panel-noteam_content">
        <div class="text">邀好友组团参加团队赛，赢万元红包大奖</div>
        <button class="btn" @click="joinBtnClick">
          {{ personInfo202310.isJoinTeam ? "我的团队" : "立即组团" }}
        </button>
      </div>
      <!-- 有团队的情况 -->
      <!-- <div class="join-panel-team_content">
        <div class="top-info">
          <div class="left-info">
            <image
              class="avatar-img"
              :src="teamInviteCompetition?.teamAvatar || IMG_URL.NO_TEAM_AVATAR"
              mode="aspectFill"
            />
            <div class="core-info">
              <div class="top-core_info">
                <div class="team-name">
                  {{ teamInviteCompetition?.teamName }}
                </div>
                <div class="total-point">
                  总积分：{{ teamInviteCompetition?.score || 0 }}
                </div>
              </div>
              <div class="bottom-core_info">
                <AuthBox
                  :hasAuth="teamInviteCompetition?.auth_status === '1'"
                  class="team-auth-box"
                />
                <div class="distance">
                  距离上一名还差：
                  <text class="num">
                    {{ teamInviteCompetition?.distance || 0 }}积分
                  </text>
                </div>
              </div>
            </div>
          </div>
          <div class="rank">{{ teamInviteCompetition?.rank || 999 }}</div>
        </div>
        <button class="btn" @click="joinBtnClick">查看我的团队</button>
      </div> -->
    </div>
    <!-- 个人巅峰赛排行榜面板 -->
    <div
      class="personal-rank-panel"
      @click="navigateTo('personal-peak-competition')"
    >
      <image class="bg" :src="IMG_URL.BOARD_BG" mode="aspectFill" />
      <image :src="IMG_URL.TROPHY" class="icon" />
      <div class="title">个人巅峰赛排行榜</div>
      <div class="tip">冠军赢苹果16pro >></div>
    </div>
    <!-- 「团队邀请赛排行榜」面板 -->
    <div
      class="team-rank-panel"
      @click="navigateTo('team-invitation-competition')"
    >
      <image class="bg" mode="aspectFill" :src="IMG_URL.BOARD_BG" />
      <image :src="IMG_URL.PEOPLE" class="icon" />
      <div class="title">团队邀请赛排行榜</div>
      <div class="tip">组团参赛赢万元红包>></div>
    </div>
    <ToLoginMask v-if="!isLogin" />
  </div>
  <!-- 提示登录条 -->
  <div v-if="!userInfo.nickname" class="login-remind">
    <text class="text"> 暂未登录，登录后才能赢取好礼 </text>
    <div class="btn" @click="navigateTo('login')">立即登录</div>
  </div>
  <RulesPopup
    ref="rulesPopup"
    :rule-key="ACTIVITY_RULE_KEY.ACTIVITY_202406"
    :title="indexPopupTitle"
    @popupClose="closePopup"
  />
  <Introduction
    ref="introduction"
    @clickRule="clickRule"
    @popupClose="closePopup"
  />
  <PointBroadPopup ref="pointBroadPopup" @popupClose="closePopup" />
  <TeamBroadPopup ref="teamBroadPopup" @popupClose="closePopup" />
  <CustomTabBar />
</template>

<script setup lang="ts">
import { reqJoinTeam, reqRecordInvite } from "@/api/activity-202310-api";
import Introduction from "@/components/activity-202405/Introduction.vue";
import RulesPopup from "@/components/activity-202405/RulesPopup.vue";
import PointBroadPopup from "@/components/activity-202410/PointBroadPopup.vue";
import TeamBroadPopup from "@/components/activity-202410/TeamBroadPopup.vue";
import CustomTabBar from "@/components/CustomTabBar.vue";
import ToLoginMask from "@/components/ToLoginMask.vue";
import { IMG_URL } from "@/static/constant/activity-202405-constant";
import { ACTIVITY_RULE_KEY } from "@/static/constant/view-constant";
import { useActivity202310 } from "@/stores/activity-202310-store";
import { useUser } from "@/stores/user";
import { inviteFriend } from "@/utils/activity-202310-utils";
import { getLocalToken } from "@/utils/local-data";
import { navigateTo } from "@/utils/navigate";
import { showToast } from "@/utils/tools";
import { showModal } from "@uni-helper/uni-promises";
import dayjs from "dayjs";

const activity202310Store = useActivity202310();
const { teamInviteCompetition, personInfo202310 } =
  storeToRefs(activity202310Store);
const { setPersonInfo202310, setTeamInviteCompetitionData } =
  activity202310Store;
const user = useUser();
const { userInfo, isLogin } = storeToRefs(user);
const { checkToken } = user;

/** 活动规则弹窗 */
const rulesPopup = ref<InstanceType<typeof RulesPopup>>();
/** 活动弹窗标题 */
const indexPopupTitle = ref("嗨喵巅峰赛活动规则");
/** 活动简介弹窗 */
const introduction = ref<InstanceType<typeof Introduction>>();
/**昨日积分广播弹窗 */
const pointBroadPopup = ref<InstanceType<typeof PointBroadPopup>>();
// 昨日团队积分广播弹窗
const teamBroadPopup = ref<InstanceType<typeof TeamBroadPopup>>();
// #region 信息的获取相关

/** 检查并获取信息 */
const checkAndGetInfo = async () => {
  if (!personInfo202310.value.userId) {
    setPersonInfo202310();
  }
};

onShow(() => {
  checkAndGetInfo();
});

// #endregion

// #region 2023年十月活动相关

/** 2023年十月活动邀请加入队伍逻辑
 * @param options 小程序onShow参数
 */
const activity202310JoinTeam = async (options?: AnyObject) => {
  const teamId = uni.getStorageSync("teamId") || options?.teamId;
  const teamName = uni.getStorageSync("teamName") || options?.teamName;
  const inviterOfJoinTeam =
    uni.getStorageSync("inviterOfJoinTeam") || options?.inviterOfJoinTeam;
  if (!teamId) return;

  const showModalRes = await showModal({
    title: `${inviterOfJoinTeam}邀请您加入Ta的团队"${teamName}",赢取万元现金红包!`,
    content: "注意：一经加入团队并产生积分后无法退出团队哦",
  });

  if (!showModalRes.confirm) return;

  if (!isLogin.value) {
    uni.setStorageSync("teamId", teamId);
    uni.setStorageSync("teamName", teamName);
    uni.setStorageSync("inviterOfJoinTeam", inviterOfJoinTeam);
    navigateTo("login");
    showToast("请先登录");
    return;
  }

  if (!personInfo202310.value.userId) {
    await setPersonInfo202310();
  }

  if (personInfo202310.value.isJoinTeam) {
    uni.showToast({
      title: "您已加入过团队，不可重复加入",
      icon: "none",
    });
    uni.removeStorageSync("teamId");
    uni.removeStorageSync("teamName");
    uni.removeStorageSync("inviterOfJoinTeam");
    return;
  }

  const joinTeamRes = await reqJoinTeam(teamId);
  if (joinTeamRes.data.data.code !== 200) {
    uni.showToast({
      title: joinTeamRes.data.data.msg || "加入团队失败",
      icon: "none",
    });
    return;
  }
  await Promise.all([setPersonInfo202310(), setTeamInviteCompetitionData()]);
  uni.showToast({
    title: "加入团队成功",
    icon: "none",
  });
  uni.removeStorageSync("teamId");
  uni.removeStorageSync("teamName");
  uni.removeStorageSync("inviterOfJoinTeam");
};

/** 2023年十月活动邀请好友逻辑
 * @param options 小程序onShow参数
 */
const activity202310InviteFriend = (options: AnyObject) => {
  const { inviteKey } = options;
  if (!getLocalToken()) {
    uni.setStorageSync("inviteKey", inviteKey);
  }
  reqRecordInvite(inviteKey);
};

onLoad((options: AnyObject | undefined) => {
  console.log("index onLoad", options);
  if (!options) return;
  checkToken();
  activity202310InviteFriend(options);
  activity202310JoinTeam(options);
});

onShow(() => {
  if (isLogin.value) {
    activity202310JoinTeam();
  }
  // 延时0.3s后再弹出弹窗 等待页面渲染完成后弹出
  setTimeout(() => {
    judgeThenPopup();
  }, 300);
});

// #endregion

// #region  弹窗相关
// 弹窗类型
// 定义弹窗的类型、决定弹出的顺序优先级
const POPUP_TYPES = {
  // introduction: "introduction", // 第一次进小程序弹出
  pointBroadPopup: "pointBroadPopup", // 每天弹出一次
  teamBroadPopup: "teamBroadPopup", // 每天弹出一次
};

// 用于记录规则弹窗的显示状态
let rulePopupVisibleWhenActive = false;
/**
 * 介绍弹窗中的「活动规则」按钮点击回调
 */
const clickRule = () => {
  // 这行代码一定要放在introduction.value?.close()之前
  // 目的：用户主动查看规则弹窗，则其他自动弹出的弹窗逻辑不再执行
  rulePopupVisibleWhenActive = true;
  introduction.value?.close();
  rulesPopup.value?.open();
};

/**
 * 弹窗关闭的回调函数
 * 当前弹窗关闭后，判断是否需要弹出下一个弹窗
 */
const closePopup = () => {
  // 如果规则弹窗是显示状态，则需要重置
  // 并且不需要执行judgeThenPopup()逻辑
  if (rulePopupVisibleWhenActive) {
    // 进入此if说明用户主动点击打开规则弹窗的情况下关闭了规则弹窗
    rulePopupVisibleWhenActive = false;
    return;
  }
  judgeThenPopup();
};

/**
 * 获取需要弹出弹窗的类型
 * 依据：1、缓存中存储 lastShowIntroductionTime: {date:'YYYY-MM-DD',hasPopupTypes:[]}
 */
const getNeedPopupType = () => {
  const storagePopupInfo = uni.getStorageSync("lastShowIntroductionTime");
  try {
    const tmpStorageObj = JSON.parse(storagePopupInfo);
    if (tmpStorageObj.date !== dayjs().format("YYYY-MM-DD")) {
      // 进入此if说明缓存中的数据不是今天的
      // 走异常分支的逻辑
      throw new Error("showFirstPopup");
    } else {
      // 进入此if说明缓存中的数据是今天的
      // 需要过滤出今天还没有弹出的弹窗类型
      const hasPopupTypes = tmpStorageObj.hasPopupTypes;
      const needPopupTypes = Object.values(POPUP_TYPES).filter(
        (popupType) => !hasPopupTypes.includes(popupType)
      );
      if (needPopupTypes.length === 0) {
        // 进入此if说明今天弹窗都已经弹出过了，不需要再弹出
        return null;
      } else {
        // 进入此else说明今天还有弹窗没有弹出，返回第一个需要弹出的弹窗类型
        return needPopupTypes[0];
      }
    }
  } catch {
    // 进入catch有以下几种可能：1、缓存中没数据 2、缓存中的数据格式不对 3、缓存中的数据不是今天的
    return POPUP_TYPES.pointBroadPopup;
  }
};

/**
 * 存储弹出信息
 */
const savePopupInfo = (popupType: string) => {
  const storagePopupInfo = uni.getStorageSync("lastShowIntroductionTime");
  let targetObj = null;
  try {
    const tmpStorageObj = JSON.parse(storagePopupInfo);
    const today = dayjs().format("YYYY-MM-DD");
    if (tmpStorageObj.date !== today) {
      // 进入此if说明缓存中的日期不是今天，需要初始化缓存
      // 通过抛出异常的方式初始化缓存
      throw new Error("init");
    } else {
      // 进入此else说明缓存中的日期是对的，将popupType添加到hasPopupTypes中
      targetObj = tmpStorageObj;
      if (!targetObj.hasPopupTypes.includes(popupType)) {
        targetObj.hasPopupTypes.push(popupType);
      }
    }
  } catch {
    // 进入此catch说明缓存中没有数据或者数据格式有问题、不符合要求，需要初始化缓存
    targetObj = {
      date: dayjs().format("YYYY-MM-DD"),
      hasPopupTypes: [popupType],
    };
  }
  uni.setStorageSync("lastShowIntroductionTime", JSON.stringify(targetObj));
};

/**
 * 显示弹窗的main方法
 */
const judgeThenPopup = () => {
  // 没有登录的情况下则只弹规则弹窗
  if (!isLogin.value) {
    judgeThenPopupRule();
    return;
  }
  // 已登录的情况下
  // 并且规则弹窗没弹过则先弹出规则弹窗
  const rulePopupResult = judgeThenPopupRule();
  if (!rulePopupResult) {
    // 进入此if说明规则弹窗已经弹出过了，可以弹出其他弹窗
    popupOther();
  }
};

/**
 * 弹出「活动规则」弹窗
 * @returns {boolean} 是否弹出规则弹窗
 */
const judgeThenPopupRule = () => {
  const storageIntroductionShowFlag = uni.getStorageSync(
    "introductionShowFlag"
  );
  if (!storageIntroductionShowFlag) {
    introduction.value?.open();
    uni.setStorageSync("introductionShowFlag", "1");
    return true;
  }
  return false;
};

/**
 * 弹出其他弹窗
 */
const popupOther = () => {
  // 获取需要弹出弹窗的类型
  const needPopupType = getNeedPopupType();
  if (!needPopupType) {
    return;
  }
  // 弹出弹窗
  if (needPopupType === POPUP_TYPES.pointBroadPopup) {
    pointBroadPopup.value?.open();
  } else if (needPopupType === POPUP_TYPES.teamBroadPopup) {
    teamBroadPopup.value?.open();
  }
  // 存储弹出信息
  savePopupInfo(needPopupType);
};

// 每天显示一次活动介绍弹窗
// onReady(() => {
//   judgeThenPopup();
// });

// #endregion

/** 分享的逻辑 */
onShareAppMessage(() => inviteFriend());

/** 点击「立即组团」按钮回调 */
const joinBtnClick = () => {
  if (personInfo202310.value.isJoinTeam) {
    navigateTo("my-team");
    return;
  }
  navigateTo("my-team-no-team");
};

/**
 * 当前页面需要用到团队信息
 * 如果加入团队了 要获取团队信息
 */
// watch(() => personInfo202310.value.isJoinTeam, (newVal) => {
//   if(newVal) {
//     setTeamInviteCompetitionData();
//   }
// })
</script>

<style lang="scss" scoped>
.login-remind {
  position: fixed;
  bottom: calc($tabBarHeight + env(safe-area-inset-bottom));
  left: 0;
  z-index: 98;

  width: 100vw;
  height: 38px;

  background: rgba($color: #000, $alpha: 60%);

  display: flex;
  align-items: center;
  justify-content: space-between;

  .text {
    margin-left: 20px;

    font-size: 15px;
    color: #fff;
  }

  .btn {
    margin-right: 16px;
    width: 60px;
    height: 22px;
    background: linear-gradient(270deg, #864ce4 0%, #272fd9);
    font-size: 11px;
    line-height: 22px;
    color: #fff;
    text-align: center;
  }
}

.page-container {
  position: relative;
  z-index: 1;

  width: 100%;
  height: 100vh;

  padding: 0 10px calc($tabBarHeight + env(safe-area-inset-bottom) + 30px);
  display: grid;
  grid-template:
    ". ." 1fr
    "join-panel join-panel" min-content
    "personal-rank-panel team-rank-panel" min-content
    / 1fr 1fr;
  gap: 10px;

  .page-bg {
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;

    width: 100vw;
    height: 100vh;
    overflow: hidden;

    background-color: #0051f4;

    &__img {
      width: 100%;
    }
  }

  .activity-rule-btn,
  .share-friend-btn {
    position: absolute;
    right: 12px;

    width: 32px;
    height: 32px;

    background-color: rgba($color: #000, $alpha: 40%);
    border-radius: 50%;

    display: flex;
    align-items: center;
    justify-content: center;

    font-size: 11px;
    color: #fff;
  }

  .activity-rule-btn {
    top: 47px;
  }

  .share-friend-btn {
    top: 87px;

    .hidden-btn {
      position: absolute;
      top: 0;
      left: 0;

      width: 100%;
      height: 100%;

      opacity: 0;
    }
  }

  .join-panel {
    grid-area: join-panel;

    position: relative;

    width: 100%;

    .join-panel-noteam_content {
      overflow: hidden;

      background-color: #fff;
      border-radius: 8px;

      padding: 16px 16px 8px;
      box-sizing: border-box;
      display: grid;
      grid-template:
        "text" min-content
        "btn" min-content
        / 1fr;
      row-gap: 12px;
      place-items: center;
      .text {
        grid-area: text;

        width: 100%;
        height: 30px;

        background-color: #ffcbd2;
        border-radius: 4px;

        display: flex;
        align-items: center;
        justify-content: center;

        font-size: 16px;
        color: #ff403c;
      }

      .btn {
        grid-area: btn;

        width: 74.9333vw;
        height: 38px;

        background: $button-bg;
        border-radius: 36px;

        animation: scale 0.4s infinite ease-in-out alternate;

        display: flex;
        align-items: center;
        justify-content: center;

        font-size: 15px;
        font-weight: bold;
        color: #fff;

        @keyframes scale {
          0% {
            transform: scale(1);
          }

          100% {
            transform: scale(1.05);
          }
        }
      }
    }
    .join-panel-team_content {
      background-color: #fff;
      border-radius: 8px;
      padding: 23rpx 19rpx;
      .top-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .left-info {
          display: flex;
          align-items: center;
          .avatar-img {
            width: 96rpx;
            height: 96rpx;
            border-radius: 50%;
            margin-right: 19rpx;
          }
          .core-info {
            .top-core_info {
              margin-bottom: 15rpx;
              display: flex;
              align-items: flex-end;
              .team-name {
                font-size: 33rpx;
                color: #333;
                max-width: 200rpx;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
              .total-point {
                font-size: 25rpx;
                color: rgba(0, 0, 0, 0.4);
                margin-left: 10rpx;
              }
            }

            .bottom-core_info {
              display: flex;
              align-items: center;
              .distance {
                margin-left: 13rpx;
                font-size: 29rpx;
                color: #333;
                .num {
                  color: #ff2459;
                }
              }
            }
          }
        }
        .rank {
          font-size: 54rpx;
          font-weight: 400;
          color: #333;
        }
      }
      .btn {
        width: 458rpx;
        background: linear-gradient(270deg, #864ce4 0%, #272fd9);
        border-radius: 52rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 25rpx;
        color: #fff;
        font-weight: 400;
        margin: 0 auto;
        margin-top: 23rpx;
      }
    }
  }

  .personal-rank-panel,
  .team-rank-panel {
    position: relative;

    width: 100%;
    overflow: hidden;

    border-radius: 8px;

    padding: 13px max(16px, 2.1333vw);
    display: grid;
    grid-template:
      "icon title" 1fr
      "icon tip" 1fr
      / auto max-content;
    column-gap: 6px;
    align-items: center;

    .bg {
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;

      width: 100%;
      height: 100%;
    }

    .icon {
      grid-area: icon;

      width: 40px;
      height: 40px;
    }

    .title {
      grid-area: title;
      align-self: flex-end;

      font-size: 3vw;
      font-weight: bold;
      color: #513b25;
    }

    .tip {
      grid-area: tip;
      align-self: flex-start;

      font-size: 2.5vw;
      color: #948470;
    }
  }

  .personal-rank-panel {
    grid-area: personal-rank-panel;
  }

  .team-rank-panel {
    grid-area: team-rank-panel;
  }
}
</style>
